<?php
/**
 * 适用于命令行触发的部署
 */

//部署脚本路径
$deployDir = __DIR__.'/'; //默认部署脚本跟本文件在同一目录
define('ROOT', str_replace('\\', '/', $deployDir));
define('CONF_DIR', ROOT.'conf/'); //存放git仓库的目录
define('REPO_DIR', ROOT.'repo/'); //存放git仓库的目录
define('LIB_DIR', ROOT.'Lib/'); //工具库目录
define('GIT_BIN', 'git');

$configs = scandir(CONF_DIR);
$configs = array_diff($configs, ['.', '..']);
foreach ($configs as $k => $file) {
    $configs[$k] = str_replace('.php', '', $file);
}

//读取命令行参数
$arrArg = getopt('c:b:t:ah'); //c: 配置文件 b: git分支名 t: git tag名 a: 全量覆盖
if (isset($arrArg['h'])) {
    foreach ($configs as $file) {
        echo '- cd '. ROOT .' && php cli.php -c '.$file.PHP_EOL;
    }
    exit;
}

if (empty($arrArg['c']) || !in_array($arrArg['c'], $configs)) {
    echo '-c 参数值不存在'.PHP_EOL.'用法举例: php cli.php -c config_name [-b branch_name] [-t tag_name] [-a]'.PHP_EOL;
    foreach ($configs as $file) {
        echo '- cd '. ROOT .' && php cli.php -c '.$file.PHP_EOL;
    }
    exit;
}

//获取需要部署的项目名称, 也是项目的目录名
$configName = $arrArg['c'];

include_once(LIB_DIR.'/GitTool.php');
include_once(LIB_DIR.'/Dir.php');

$tool = new GitTool();
$tool->ini($configName);
$tool->isShowResult = true;
$tool->eof = PHP_EOL;
$tool->logPath = ROOT.'msg.log';

//切换git仓库为指定版本的代码
if (!empty($arrArg['b'])) {
    $branchName = trim($arrArg['b']);
    $tool->switchBranch($branchName);
} elseif (!empty($arrArg['t'])) {
    $tagName = trim($arrArg['t']);
    $tool->switchTag($tagName);
} else {
    $tool->switchBranch('master'); //默认切换为master分支
}

$fullCopy = (isset($arrArg['a']) || !empty($arrArg['t'])) ? true : false;
if ($fullCopy) {
    $tool->deployAll(); //全量部署
} else {
    $tool->deployPart(); //增量部署
}

$tool->clearCache()
    ->cmd()
    ->changeAuth()
    ->over();

echo 'over~';